using System;
using System.Windows.Input;
using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Composite.Presentation.Commands;
using Microsoft.Practices.Unity;
using Silverlight.Weblog.Client.DAL.Events;
using Silverlight.Weblog.Client.DAL.Services;
using Silverlight.Weblog.Client.DAL.ViewModel;
using Silverlight.Weblog.Common.IoC;
using Silverlight.Weblog.Server.DAL;

namespace Silverlight.Weblog.Client.Default.Widgets
{
    public class SearchbarWidgetViewModel : ViewModelBase, ISearchbarWidgetViewModel, IDisposable
    {
        public SearchbarWidgetViewModel()
        {
            IoC.Get<IEventAggregator>().GetEvent<InitiaPayloadLoadedEvent>().Subscribe(UpdateModel);

            SearchAction = new DelegateCommand<object>(OnSearchAction);
        }

        public void UpdateModel(User obj)
        {
            this.Model = obj;
        }

        private void OnSearchAction(object obj)
        {
            IoC.Get<IEventAggregator>().GetEvent<SearchTermEvent>().Publish(new SearchEventData(SearchTerm, Model != null ? Model.Username : string.Empty));;
        }


        #region SearchTerm
        private string _searchTerm;
        public string SearchTerm
        {
            get { return _searchTerm; }
            set
            {
                if (_searchTerm != value)
                {
                    _searchTerm = value;
                    RaisePropertyChanged("SearchTerm");
                }

            }
        }
        #endregion SearchTerm

        #region SearchAction
        private ICommand _searchAction;
        public ICommand SearchAction
        {
            get { return _searchAction; }
            set
            {
                if (_searchAction != value)
                {
                    _searchAction = value;
                    RaisePropertyChanged("SearchAction");
                }

            }
        }
        #endregion SearchAction

        #region Model
        private User _model;
        public User Model
        {
            get { return _model; }
            set
            {
                if (_model != value)
                {
                    _model = value;
                    RaisePropertyChanged("Model");
                }

            }
        }
        #endregion Model

        #region Implementation of IDisposable

        public void Dispose()
        {
            IoC.Get<IEventAggregator>().GetEvent<InitiaPayloadLoadedEvent>().Unsubscribe(UpdateModel);
        }

        #endregion
    }
}